import { CloudDBZoneWrapper } from '../clouddb/CloudDBZoneWrapper.js';
import * as Utils from '../utils/Utils';

const TAG: string = "cloudDB-->"

/**
 * client HttpRequest
 * @param event {"id":3,"bornYear":2020,"bornName":"鼠"}或 {"bornYear":2020,"bornName":"鼠"}
 * @param context
 * @param callback
 * @param logger
 */
let myHandler = async function (event, context, callback, logger) {
  const credential = Utils.getCredential(context, logger);

  try {
    const cloudDBZoneWrapper = new CloudDBZoneWrapper(credential, logger);
    let born = cloudDBZoneWrapper.getBorn(event);

    // 先检查该年份的生肖信息在数据库中存不存在，如果存在，则不添加
    let borns = await cloudDBZoneWrapper.queryDataByYear(born.bornYear);
    if (borns.length > 0) { //说明已存在
      callback({
        result: { code: -3, desc: "EXISTS" }
      })
      return;
    }

    let result = await cloudDBZoneWrapper.insertRecord(born);
    if (result) {
      callback({
        result: { code: 0, desc: "SUCCESS" }
      });
    } else {
      callback({
        result: { code: -1, desc: "FAILED" }
      });
    }
  } catch (err) {
    logger.error(TAG + "func error:" + err.message + " stack:" + err.stack);
    callback({
      result: { code: -1, desc: "ERROR" },
    });
  }
}

export { myHandler }
